package com.self.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.self.member.dto.UserDto;
import com.self.member.feign.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.self.admin.mapper.WorkIssueMapper;
import com.self.admin.model.WorkIssue;
import com.self.admin.service.WorkIssueService;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Service
public class WorkIssueServiceImpl extends ServiceImpl<WorkIssueMapper, WorkIssue> implements WorkIssueService{

    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public Page<WorkIssue> findByPage(Page<WorkIssue> page, Integer status, String startTime, String endTime) {
        Page<WorkIssue> issuePage = page(page, new LambdaQueryWrapper<WorkIssue>()
                .eq(status != null, WorkIssue::getStatus, status)
                .between(!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime),
                        WorkIssue::getCreated, startTime, endTime + " 23:59:59"));
        if (CollectionUtils.isEmpty(issuePage.getRecords())){
            return issuePage;
        }
        List<Long> collect = issuePage.getRecords().stream().map(WorkIssue::getUserId).collect(Collectors.toList());
        List<UserDto> basicUsers = userFeignClient.getBasicUsers(collect);
        if (CollectionUtils.isEmpty(basicUsers)){
            return issuePage;
        }
        Map<Long, UserDto> userDtoMap = basicUsers.stream().collect(Collectors.toMap(userDto -> userDto.getId(), userDto -> userDto));
        issuePage.getRecords().forEach(record -> {
            UserDto userDto = userDtoMap.get(record.getUserId());
            record.setUsername(userDto== null?record.getUserId()+"":userDto.getUsername());
            record.setRealName(userDto== null?record.getUserId()+"":userDto.getRealName());
        });
        return issuePage;
    }

    /**
     * 前台系统查询客户工单
     *
     * @param page
     * @return
     */
    @Override
    public Page<WorkIssue> getIssueList(Page<WorkIssue> page,Long userId) {
        return page(page,new LambdaQueryWrapper<WorkIssue>()
                        .eq(WorkIssue::getUserId,userId)
//                                            .eq(WorkIssue::getStatus,1)
        );
    }
}
